<script setup lang="ts">
import { computed, shallowRef, onMounted, watch, ref } from 'vue';
import { $t } from '@/locales';
import { queryMenuPermission, queryPermissionIdsWithRoleId, add } from '@/service/api/system-manage';

defineOptions({ name: 'ButtonAuthModal' });

interface Props {
  /** the roleId */
  roleId: number;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

function closeModal() {
  visible.value = false;
}

const title = computed(() => $t('common.edit') + ' 权限配置');

// 树形权限数据
const permissionTree = ref<any[]>([]);
// 选中的权限ID列表
const checkedPermissionIds = ref<number[]>([]);
// 加载状态
const loading = ref<boolean>(false);
const submitLoading = ref<boolean>(false);

// 权限树配置
const defaultProps = {
  children: 'children',
  label: 'title'
};

/**
 * 获取所有权限菜单树
 */
async function getPermissionTree() {
  loading.value = true;
  try {
    const { data } = await queryMenuPermission();
    if (data) {
      permissionTree.value = data;
    }
  } catch (error) {
    console.error('获取权限菜单树失败:', error);
    window.$message?.error('获取权限菜单树失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 获取角色已分配的权限ID列表
 */
async function getRolePermissionIds() {
  loading.value = true;
  try {
    if (!props.roleId) return;
    
    const { data } = await queryPermissionIdsWithRoleId(props.roleId);
    if (data) {
      checkedPermissionIds.value = data;
    }
  } catch (error) {
    console.error('获取角色权限IDs失败:', error);
    window.$message?.error('获取角色权限列表失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 处理节点选择变化
 */
function handleCheck(data: any, checked: any) {
  checkedPermissionIds.value = checked.checkedKeys;
}

/**
 * 提交权限更新
 */
async function handleSubmit() {
  if (!props.roleId) {
    window.$message?.warning('请选择角色');
    return;
  }

  submitLoading.value = true;
  try {
    // 构造提交参数，符合SysRolePermissionUpdateDTO格式
    const params = {
      roleId: props.roleId,
      permissionIds: checkedPermissionIds.value
    };

    await add(params);
    window.$message?.success('权限更新成功');
    closeModal();
  } catch (error) {
    console.error('提交权限配置失败:', error);
    window.$message?.error('提交失败');
  } finally {
    submitLoading.value = false;
  }
}

/**
 * 初始化数据
 */
function init() {
  checkedPermissionIds.value = [];
  getPermissionTree();
  getRolePermissionIds();
}

// 监听对话框显示状态
watch(visible, (newVal) => {
  if (newVal && props.roleId) {
    init();
  }
});

// 监听角色ID变化
watch(() => props.roleId, (newVal) => {
  if (visible.value && newVal) {
    init();
  }
});

// 组件挂载时如果对话框可见则初始化
onMounted(() => {
  if (visible.value && props.roleId) {
    init();
  }
});
</script>

<template>
  <ElDialog v-model="visible" :title="title" width="600px" destroy-on-close>
    <div v-loading="loading" class="h-400px overflow-auto">
      <ElTree
        ref="permissionTree"
        node-key="id"
        :data="permissionTree"
        :props="defaultProps"
        :default-checked-keys="checkedPermissionIds"
        :default-expanded-keys="checkedPermissionIds"
        show-checkbox
        @check="handleCheck"
      />
    </div>
    <template #footer>
      <ElSpace class="w-full justify-end">
        <ElButton @click="closeModal">{{ $t('common.cancel') }}</ElButton>
        <ElButton 
          type="primary" 
          :loading="submitLoading" 
          @click="handleSubmit"
        >
          {{ $t('common.confirm') }}
        </ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>

<style scoped>
/* 自定义样式区域 */
</style>
